<template>
  <div class="analysis-dashboard">
    <div class="page-header">
      <div class="header-left">
        <h1>数据分析看板</h1>
        <p class="header-subtitle">深度洞察客户流失模式，助力精准决策</p>
      </div>
      <div class="filter-section">
        <div class="filter-group">
          <label>时间范围</label>
          <el-select v-model="timeRange" placeholder="选择时间范围" size="default">
            <el-option label="最近30天" value="30days" />
            <el-option label="最近90天" value="90days" />
            <el-option label="最近180天" value="180days" />
            <el-option label="最近一年" value="1year" />
            <el-option label="全部数据" value="all" />
          </el-select>
        </div>

        <div class="filter-group">
          <label>客户群体</label>
          <el-select v-model="customerSegment" placeholder="选择客户群体" size="default">
            <el-option label="全部客户" value="all" />
            <el-option label="高价值客户" value="high_value" />
            <el-option label="中等价值客户" value="medium_value" />
            <el-option label="低价值客户" value="low_value" />
            <el-option label="新客户" value="new" />
          </el-select>
        </div>
      </div>
    </div>
    
    <!-- 错误提示 -->
    <el-alert
      v-if="hasError"
      title="加载图表出错"
      :description="errorMessage"
      type="error"
      show-icon
      :closable="false"
      class="mb-4"
    >
      <template #default>
        <div class="mt-10">
          <el-button type="primary" size="small" @click="retryLoading">重试</el-button>
        </div>
      </template>
    </el-alert>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 图表内容 -->
    <div v-else class="charts-container">
      <!-- 特征重要性分析 -->
      <el-row :gutter="24" class="mb-6">
        <el-col :span="24">
          <el-card shadow="hover" class="analysis-card feature-card">
            <template #header>
              <div class="card-header">
                <div class="header-content">
                  <h3>特征重要性分析</h3>
                  <p>显示对客户流失影响最大的因素</p>
                </div>
                <div class="header-icon">
                  <el-icon><TrendCharts /></el-icon>
                </div>
              </div>
            </template>
            <div class="chart-container" ref="featureImportanceChart"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 流失原因与客户特征 -->
      <el-row :gutter="24" class="mb-6">
        <el-col :xs="24" :lg="12" class="mb-xs-6">
          <el-card shadow="hover" class="analysis-card reason-card">
            <template #header>
              <div class="card-header">
                <div class="header-content">
                  <h3>流失原因分布</h3>
                  <p>各种流失原因的占比分析</p>
                </div>
                <div class="header-icon">
                  <el-icon><PieChart /></el-icon>
                </div>
              </div>
            </template>
            <div class="chart-container" ref="churnReasonChart"></div>
          </el-card>
        </el-col>

        <el-col :xs="24" :lg="12">
          <el-card shadow="hover" class="analysis-card segment-card">
            <template #header>
              <div class="card-header">
                <div class="header-content">
                  <h3>客户细分流失比例</h3>
                  <p>不同客户群体的流失比例</p>
                </div>
                <div class="header-icon">
                  <el-icon><DataAnalysis /></el-icon>
                </div>
              </div>
            </template>
            <div class="chart-container" ref="customerSegmentChart"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 相关性矩阵和服务类型分析 -->
      <el-row :gutter="24" class="mb-6">
        <el-col :xs="24" :lg="12" class="mb-xs-6">
          <el-card shadow="hover" class="analysis-card correlation-card">
            <template #header>
              <div class="card-header">
                <div class="header-content">
                  <h3>特征相关性矩阵</h3>
                  <p>特征之间的相关关系分析</p>
                </div>
                <div class="header-icon">
                  <el-icon><DataAnalysis /></el-icon>
                </div>
              </div>
            </template>
            <div class="chart-container" ref="correlationMatrix"></div>
          </el-card>
        </el-col>

        <el-col :xs="24" :lg="12">
          <el-card shadow="hover" class="analysis-card service-card">
            <template #header>
              <div class="card-header">
                <div class="header-content">
                  <h3>服务类型与流失率</h3>
                  <p>不同服务类型的客户流失率</p>
                </div>
                <div class="header-icon">
                  <el-icon><TrendCharts /></el-icon>
                </div>
              </div>
            </template>
            <div class="chart-container" ref="serviceTypeChart"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 流失风险分布 -->
      <el-row :gutter="24">
        <el-col :span="24">
          <el-card shadow="hover" class="analysis-card risk-card">
            <template #header>
              <div class="card-header">
                <div class="header-content">
                  <h3>流失风险分布</h3>
                  <p>客户流失风险评分分布情况</p>
                </div>
                <div class="header-icon">
                  <el-icon><DataAnalysis /></el-icon>
                </div>
              </div>
            </template>
            <div class="chart-container" ref="riskDistributionChart"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup name="AnalysisDashboard">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { TrendCharts, PieChart, DataAnalysis } from '@element-plus/icons-vue'

// 状态变量
const loading = ref(true)
const hasError = ref(false)
const errorMessage = ref('')

// 筛选变量
const timeRange = ref('30days')
const customerSegment = ref('all')

// 图表引用
const featureImportanceChart = ref(null)
const churnReasonChart = ref(null)
const customerSegmentChart = ref(null)
const correlationMatrix = ref(null)
const serviceTypeChart = ref(null)
const riskDistributionChart = ref(null)

// 图表实例
let charts = {
  featureImportance: null,
  churnReason: null,
  customerSegment: null,
  correlation: null,
  serviceType: null,
  riskDistribution: null
}

// 模拟数据 - 特征重要性
const featureImportanceData = {
  features: ['合同类型', '月费用', '使用期限', '互联网服务', '客户服务', '支付方式', '年龄', '套餐内容', '是否有伴侣', '性别'],
  values: [0.25, 0.18, 0.15, 0.12, 0.09, 0.08, 0.05, 0.04, 0.03, 0.01]
}

// 模拟数据 - 流失原因分布
const churnReasonData = [
  { value: 35, name: '价格因素' },
  { value: 25, name: '竞争对手' },
  { value: 18, name: '服务质量' },
  { value: 12, name: '功能不足' },
  { value: 7, name: '需求变化' },
  { value: 3, name: '其他' }
]

// 模拟数据 - 客户细分
const customerSegmentData = {
  categories: ['高价值客户', '中等价值客户', '低价值客户', '新客户'],
  total: [1200, 2800, 1800, 1200],
  churn: [120, 252, 360, 180]
}

// 模拟数据 - 相关性矩阵
const correlationData = [
  [0, 0, 1], [0, 1, 0.8], [0, 2, 0.6], [0, 3, 0.4], [0, 4, 0.2], [0, 5, 0.1],
  [1, 0, 0.8], [1, 1, 1], [1, 2, 0.3], [1, 3, 0.7], [1, 4, 0.5], [1, 5, 0.2],
  [2, 0, 0.6], [2, 1, 0.3], [2, 2, 1], [2, 3, 0.2], [2, 4, 0.6], [2, 5, 0.3],
  [3, 0, 0.4], [3, 1, 0.7], [3, 2, 0.2], [3, 3, 1], [3, 4, 0.3], [3, 5, 0.5],
  [4, 0, 0.2], [4, 1, 0.5], [4, 2, 0.6], [4, 3, 0.3], [4, 4, 1], [4, 5, 0.2],
  [5, 0, 0.1], [5, 1, 0.2], [5, 2, 0.3], [5, 3, 0.5], [5, 4, 0.2], [5, 5, 1]
]

// 模拟数据 - 服务类型与流失率
const serviceTypeData = {
  services: ['基础套餐', '标准套餐', '高级套餐', '定制套餐', '商业套餐'],
  churnRates: [14.2, 8.5, 3.7, 5.8, 7.2]
}

// 模拟数据 - 风险分布
const riskDistributionData = {
  ranges: ['0-10%', '10-20%', '20-30%', '30-40%', '40-50%', '50-60%', '60-70%', '70-80%', '80-90%', '90-100%'],
  counts: [2500, 2200, 1800, 1300, 900, 600, 380, 250, 150, 70]
}

// 创建基础图表
const createChart = (container) => {
  if (!container || !container.value) {
    console.error('图表容器不存在');
    return null;
  }

  try {
    const element = container.value;

    // 确保容器已渲染并有尺寸
    if (element.clientWidth === 0 || element.clientHeight === 0) {
      console.warn('容器尺寸为0，设置默认尺寸');
      element.style.width = '100%';
      element.style.height = '400px';
    }

    console.log(`容器尺寸:`, element.clientWidth, element.clientHeight);

    // 创建图表实例
    const chart = echarts.init(element);
    console.log('图表实例创建成功');
    return chart;
  } catch (err) {
    console.error('创建图表失败:', err);
    return null;
  }
}

// 初始化特征重要性图表
const initFeatureImportanceChart = () => {
  const container = featureImportanceChart.value;
  if (!container) {
    return null;
  }

  try {
    const chart = echarts.init(container);

    const option = {
      title: {
        text: '特征重要性分析',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        left: '25%',
        right: '10%',
        bottom: '10%',
        top: '15%'
      },
      xAxis: {
        type: 'value',
        name: '重要性'
      },
      yAxis: {
        type: 'category',
        data: featureImportanceData.features
      },
      series: [{
        name: '重要性',
        type: 'bar',
        data: featureImportanceData.values,
        itemStyle: {
          color: '#409EFF'
        }
      }]
    };

    chart.setOption(option);

    // 延迟重绘
    setTimeout(() => {
      chart.resize();
    }, 200);

    return chart;
  } catch (error) {
    console.error('特征重要性图表创建失败:', error);
    return null;
  }
}

// 初始化流失原因图表
const initChurnReasonChart = () => {
  const container = churnReasonChart.value;
  if (!container) {
    return null;
  }

  try {
    const chart = echarts.init(container);

    const option = {
      title: {
        text: '流失原因分布',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        top: 'middle'
      },
      series: [{
        name: '流失原因',
        type: 'pie',
        radius: '60%',
        center: ['60%', '50%'],
        data: churnReasonData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    };

    chart.setOption(option);

    // 延迟重绘
    setTimeout(() => {
      chart.resize();
    }, 200);

    return chart;
  } catch (error) {
    console.error('流失原因图表创建失败:', error);
    return null;
  }
}

// 初始化客户细分流失比例图表
const initCustomerSegmentChart = () => {
  console.log('初始化客户细分流失比例图表');
  const chart = createChart(customerSegmentChart);
  if (!chart) return null;
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['总客户数', '流失客户数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: customerSegmentData.categories
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '总客户数',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        itemStyle: { color: '#409eff' },
        data: customerSegmentData.total
      },
      {
        name: '流失客户数',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        itemStyle: { color: '#f56c6c' },
        data: customerSegmentData.churn
      }
    ]
  };
  
  chart.setOption(option);
  console.log('客户细分流失比例图表配置完成');
  return chart;
}

// 初始化相关性矩阵
const initCorrelationMatrix = () => {
  console.log('初始化相关性矩阵');
  const chart = createChart(correlationMatrix);
  if (!chart) return null;
  
  const features = ['合同', '月费用', '期限', '网络', '客服', '支付方式'];
  
  const option = {
    tooltip: {
      position: 'top'
    },
    grid: {
      height: '70%',
      top: '10%'
    },
    xAxis: {
      type: 'category',
      data: features,
      splitArea: {
        show: true
      }
    },
    yAxis: {
      type: 'category',
      data: features,
      splitArea: {
        show: true
      }
    },
    visualMap: {
      min: -1,
      max: 1,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '0%',
      inRange: {
        color: ['#d94e5d', '#eac736', '#50a3ba']
      }
    },
    series: [
      {
        name: '相关系数',
        type: 'heatmap',
        data: correlationData,
        label: {
          show: true
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  
  chart.setOption(option);
  console.log('相关性矩阵配置完成');
  return chart;
}

// 初始化服务类型图表
const initServiceTypeChart = () => {
  console.log('初始化服务类型图表');
  const chart = createChart(serviceTypeChart);
  if (!chart) return null;
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {},
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01],
      axisLabel: {
        formatter: '{value}%'
      }
    },
    yAxis: {
      type: 'category',
      data: serviceTypeData.services
    },
    series: [
      {
        name: '流失率',
        type: 'bar',
        data: serviceTypeData.churnRates,
        itemStyle: {
          color: function(params) {
            // 根据流失率设置不同的颜色
            const value = params.value;
            if (value > 10) return '#f56c6c'; // 红色
            if (value > 7) return '#e6a23c';  // 黄色
            return '#67c23a';                  // 绿色
          }
        }
      }
    ]
  };
  
  chart.setOption(option);
  console.log('服务类型图表配置完成');
  return chart;
}

// 初始化风险分布图表
const initRiskDistributionChart = () => {
  console.log('初始化风险分布图表');
  const chart = createChart(riskDistributionChart);
  if (!chart) return null;
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: riskDistributionData.ranges,
        axisLabel: {
          interval: 0,
          rotate: 45
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '客户数量',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        itemStyle: {
          color: '#409eff'
        },
        data: riskDistributionData.counts
      }
    ]
  };
  
  chart.setOption(option);
  console.log('风险分布图表配置完成');
  return chart;
}



// 初始化所有图表
const initAllCharts = async () => {
  // 不要设置loading为true，因为这会隐藏容器
  hasError.value = false;
  errorMessage.value = '';

  try {
    // 先销毁现有图表
    Object.values(charts).forEach(chart => {
      if (chart) {
        try {
          chart.dispose();
        } catch (e) {
          console.error('销毁图表失败:', e);
        }
      }
    });

    // 重置图表对象
    charts = {
      featureImportance: null,
      churnReason: null,
      customerSegment: null,
      correlation: null,
      serviceType: null,
      riskDistribution: null
    };

    // 等待DOM渲染完成
    await nextTick();

    // 添加延迟确保容器完全渲染
    await new Promise(resolve => setTimeout(resolve, 50));

    // 逐个初始化图表，避免并发问题
    console.log('开始初始化图表...');

    // 初始化主要图表
    charts.featureImportance = initFeatureImportanceChart();
    charts.churnReason = initChurnReasonChart();

    // 延迟初始化其他图表，提高页面响应速度
    setTimeout(() => {
      charts.customerSegment = initCustomerSegmentChart();
      charts.correlation = initCorrelationMatrix();
      charts.serviceType = initServiceTypeChart();
      charts.riskDistribution = initRiskDistributionChart();
    }, 100);

    console.log('所有图表初始化完成');
  } catch (error) {
    console.error('初始化图表过程中出错:', error);
    hasError.value = true;
    errorMessage.value = `图表初始化失败: ${error.message}`;
  } finally {
    // loading状态保持false，确保容器始终可见
  }
}

// 重试加载图表
const retryLoading = () => {
  console.log('重试加载图表');
  initAllCharts();
}







// 处理窗口大小变化，重绘图表
const handleResize = () => {
  if (hasError.value) return;

  Object.values(charts).forEach(chart => {
    if (chart) {
      try {
        chart.resize();
      } catch (e) {
        console.error('调整图表大小失败:', e);
      }
    }
  });
}







onMounted(async () => {
  window.addEventListener('resize', handleResize);

  // 设置loading为false，确保DOM元素被渲染
  loading.value = false;

  // 等待DOM完全渲染后初始化图表
  await nextTick();

  // 延迟初始化图表，确保容器已渲染
  setTimeout(() => {
    initAllCharts();
  }, 300);
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  
  // 销毁图表实例
  Object.values(charts).forEach(chart => {
    if (chart) {
      try {
        chart.dispose();
      } catch (e) {
        console.error('销毁图表失败:', e);
      }
    }
  });
})
</script>

<style lang="scss" scoped>
.analysis-dashboard {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 60px);

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 32px;
    padding: 24px;
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);

    .header-left {
      h1 {
        margin: 0 0 8px 0;
        font-size: 28px;
        font-weight: 600;
        color: #1a202c;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }

      .header-subtitle {
        margin: 0;
        font-size: 16px;
        color: #718096;
        font-weight: 400;
      }
    }

    .filter-section {
      display: flex;
      gap: 20px;

      .filter-group {
        display: flex;
        flex-direction: column;
        gap: 8px;

        label {
          font-size: 14px;
          font-weight: 500;
          color: #4a5568;
        }

        .el-select {
          width: 160px;
        }
      }
    }
  }

  .analysis-card {
    border-radius: 16px;
    border: none;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    overflow: hidden;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
    }

    :deep(.el-card__header) {
      padding: 24px;
      border-bottom: 1px solid #e2e8f0;
      background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    }

    :deep(.el-card__body) {
      padding: 24px;
      height: 400px;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-content {
        h3 {
          margin: 0 0 4px 0;
          font-size: 18px;
          font-weight: 600;
          color: #2d3748;
        }

        p {
          margin: 0;
          font-size: 14px;
          color: #718096;
        }
      }

      .header-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;

        .el-icon {
          font-size: 24px;
        }
      }
    }

    // 不同卡片的主题色
    &.feature-card .header-icon {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }

    &.reason-card .header-icon {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      color: white;
    }

    &.segment-card .header-icon {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      color: white;
    }

    &.correlation-card .header-icon {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      color: white;
    }

    &.service-card .header-icon {
      background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
      color: white;
    }

    &.risk-card .header-icon {
      background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
      color: #2d3748;
    }
  }

  .chart-container {
    height: 320px;
    width: 100%;
    min-height: 320px;
    position: relative;
    border-radius: 12px;
    background: #ffffff;
    display: block !important;

    // 移除可能影响图表显示的样式
    canvas {
      display: block !important;
    }
  }

  .mb-6 {
    margin-bottom: 32px;
  }

  .mb-xs-6 {
    @media (max-width: 992px) {
      margin-bottom: 32px;
    }
  }

  .loading-container {
    padding: 40px;
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  }

  .el-alert {
    border-radius: 12px;
    margin-bottom: 24px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .analysis-dashboard {
    padding: 16px;

    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 20px;

      .filter-section {
        flex-direction: column;
        gap: 16px;

        .filter-group .el-select {
          width: 100%;
        }
      }
    }

    .analysis-card {
      :deep(.el-card__body) {
        height: 300px;
      }

      .chart-container {
        height: 240px;
      }
    }
  }
}
</style>